import { defineConfig, UserConfig, mergeConfig } from "vite";
import vuePlugin from "@vitejs/plugin-vue";
import path from "path";
import { buildPlugin, Options as BuildOptions } from "vite-plugin-build";
import * as packages from "./package.json";
import * as lodash from "lodash";

const devDependencies = lodash.keys(packages);

// @ts-ignore
export default defineConfig(({ command, mode }) => {
  console.log(command, mode);

  const plugins = [vuePlugin()];

  let build: UserConfig = {};
  if (command === "build") {
    const buildOptions: BuildOptions = {
      fileBuild: {
        inputFolder: "src",
        emitDeclaration: true,
        esOutputDir: "build/es",
        commonJsOutputDir: "build/lib",
      },
      libBuild: {
        buildOptions: {
          outDir: "build",
          rollupOptions: {
            external: devDependencies,
          },
          lib: {
            entry: path.resolve(__dirname, "src/index.ts"),
            name: "ysTs",
            fileName: (format) => `ys-ts.${format}.js`,
          },
        },
      },
    };
    build = {
      plugins: [buildPlugin(buildOptions)],
    };
  }

  let server: UserConfig = {};
  if (command === "serve") {
    server = {
      publicDir: "examples/public",
      resolve: { alias: {} },
    };
    if (mode === "development") {
      server.resolve.alias = {
        "@ys-lib": path.resolve(__dirname, "src"),
      };
    } else {
      server.resolve.alias = {
        "@ys-lib": path.resolve(__dirname, "build/es"),
      };
    }
  }

  // 组合配置参数
  let obj: UserConfig = {
    plugins: [vuePlugin()],
    css: {
      modules: {
        localsConvention: "camelCaseOnly",
        generateScopedName: (name: string) => `ys-${name}`,
      },
    },
  };

  // 合并 server 模式配置
  obj = mergeConfig(obj, build);
  obj = mergeConfig(obj, server);

  return obj;
});
